package com.ruoyi.energy.config;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

/**
 * TDengine 时序数据库配置
 * 
 * @author ruoyi
 * @date 2025-01-28
 */
@Configuration
public class TDengineConfig {

    @Value("${tdengine.datasource.url:jdbc:TAOS://localhost:6030/}")
    private String url;

    @Value("${tdengine.datasource.username:root}")
    private String username;

    @Value("${tdengine.datasource.password:taosdata}")
    private String password;

    @Value("${tdengine.datasource.driver-class-name:com.taosdata.jdbc.TSDBDriver}")
    private String driverClassName;

    @Value("${tdengine.datasource.maximum-pool-size:10}")
    private int maximumPoolSize;

    @Value("${tdengine.datasource.minimum-idle:5}")
    private int minimumIdle;

    @Value("${tdengine.datasource.connection-timeout:30000}")
    private long connectionTimeout;

    @Value("${tdengine.datasource.idle-timeout:600000}")
    private long idleTimeout;

    @Value("${tdengine.datasource.max-lifetime:1800000}")
    private long maxLifetime;

    /**
     * TDengine数据源配置
     */
    @Bean(name = "tdengineDataSource")
    public DataSource tdengineDataSource() {
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl(url);
        config.setUsername(username);
        config.setPassword(password);
        config.setDriverClassName(driverClassName);
        config.setMaximumPoolSize(maximumPoolSize);
        config.setMinimumIdle(minimumIdle);
        config.setConnectionTimeout(connectionTimeout);
        config.setIdleTimeout(idleTimeout);
        config.setMaxLifetime(maxLifetime);
        
        // TDengine特定配置
        config.addDataSourceProperty("useSSL", "false");
        config.addDataSourceProperty("allowPublicKeyRetrieval", "true");
        config.addDataSourceProperty("batchfetch", "true");
        config.addDataSourceProperty("timestampFormat", "STRING");

        // 连接验证配置
        config.setConnectionTestQuery("SELECT SERVER_VERSION()");
        config.setLeakDetectionThreshold(60000);
        config.setValidationTimeout(5000);
        
        return new HikariDataSource(config);
    }

    /**
     * TDengine JdbcTemplate
     */
    @Bean(name = "tdengineJdbcTemplate")
    public JdbcTemplate tdengineJdbcTemplate() {
        return new JdbcTemplate(tdengineDataSource());
    }
} 